package com.xtourms.client.ui.util;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.TextBox;

public class MoneyTextBox extends TextBox{
	
	public MoneyTextBox(){
		addValueChangeHandler(new ValueChangeHandler<String>() {
			
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				String input = event.getValue();
				if(!isValid(input)){
					MessageBox.ins.showWarning("金额输入不合法");
				}
			}
		});
	}
	
	public boolean isValid(){
		return isValid(super.getValue());
	}
	
	private boolean isValid(String input) {
		int point = input.indexOf(".");
		if(-1 != point){
			String yuan = input.substring(0, point);
			if(point == input.length()){
				return false;
			}
			String fen = input.substring(point+1);
			try{
				Integer.parseInt(yuan);
				Integer.parseInt(fen);
			}catch (NumberFormatException e) {
				return false;
			}
		}else{
			try{
				Integer.parseInt(input);
			}catch (NumberFormatException e) {
				return false;
			}
		}
		return true;
	}
	
	public int getMoney(){
		int ret = 0;
		String money = super.getValue();
		if(money.isEmpty()){
			return -1;
		}
		int point = money.indexOf(".");
		
		if(-1 != point){
			String yuan = money.substring(0, point);
			if(point != money.length()){
				String fen = money.substring(point+1);
				ret = Integer.parseInt(yuan)*100+Integer.parseInt(fen);
			}else{
				ret = Integer.parseInt(yuan)*100;
			}
		}else{
			ret = Integer.parseInt(money)*100;
		}
		return ret;
	}
	
	public void setMoney(String fen){
		int coin = Integer.parseInt(fen);
		String money = coin/100 +"."+ coin%100;
		super.setValue(money);
	}
	
}
